Page({
  /**
   * 页面的初始数据
   */
  data: {
    show1: false,
    show2: false,
    currentDate1: new Date().getTime(),
    currentDate2: new Date().getTime(),
    minDate: new Date().getTime() - 3600 * 1000 * 24 * 365, // 最小日期为当前日期前一年
    maxDate: new Date().getTime() + 3600 * 1000 * 24 * 365 * 5, // 最大日期为当前日期后一年
    minDate1: new Date().getTime() - 3600 * 1000 * 24 * 365, // 最小日期为当前日期前一年
    maxDate1: new Date().getTime() + 3600 * 1000 * 24 * 365 * 5, // 最大日期为当前日期后一年
    // minDate3: new Date(2019, 10, 1).getTime(),
    formatter1(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    formatter2(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    showPopup: false, // 控制弹出层显示与隐藏
    showPopup1: false, // 控制弹出层显示与隐藏
    user: "",
    manufactor: [],
    orderNumber: "",
    taobaoNumber: "",
    // oddNumber: "",
    orderTime: "", //数据库的时间
    advancePayment: "",
    expectDeliTime: "",
    realityTime: "",
    customerAddress: "",
    remarks: "",
    billingType: "notHave",  //开票类型
    orderCompleted: "no",
    afterSale: "no",
    userList: [],
    manufacturerList: [],

  },
  // 填充下单时间
  addTime(){
    const datePart = this.data.orderNumber.substring(1, 9);
    const formattedDate = `${datePart.substring(0, 4)}-${datePart.substring(4, 6)}-${datePart.substring(6, 8)}`;
    this.setData({
      orderTime:formattedDate
    })
  },

  onDisplay1() {
    this.setData({
      show1: true,

    })
  },
  onDisplay2() {
    this.setData({
      show2: true,
    })
  },
  // 关闭下单时间弹框
  offTpu() {
    this.setData({
      show: false,
      orderTime:"",
    })
  },
  offTpu1() {
    this.setData({
      show1: false,
      expectDeliTime:""
    })
  },
  offTpu2() {
    this.setData({
      show2: false,
      realityTime:""
    })
  },

  onInput1(event) {
    const timestamp = event.detail;
    const formattedDate = this.formatTimestampToDate(timestamp);
    this.setData({
      expectDeliTime: formattedDate,
      show1: false
    });
  },
  onInput2(event) {
    const timestamp = event.detail;
    const formattedDate = this.formatTimestampToDate(timestamp);
    this.setData({
      realityTime: formattedDate,
      show2: false
    });
  },
  // 转换日期
  formatTimestampToDate(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
  },

  // 点击按钮显示弹出层
  showPopup() {
    this.setData({
      showPopup: true
    });
  },
  showPopup1() {
    this.setData({
      showPopup1: true
    });
  },
  // 关闭弹出层时触发
  onClosePopup() {
    this.setData({
      showPopup: false
    });
  },
  onClosePopup1() {
    this.setData({
      showPopup1: false
    });
  },
  // 点击选择器取消按钮时触发
  onCancelPicker() {
    this.setData({
      showPopup: false
    });
  },
  onCancelPicker1() {
    this.setData({
      showPopup1: false,
      manufactor: []
    });
    console.log(this.data.manufactor)
  },
  // 点击选择器确认按钮时触发
  onConfirmPicker(event) {
    const {
      value
    } = event.detail;
    this.setData({
      showPopup: false,
      user: value
    });
  },
  onConfirmPicker1(event) {
    const {
      value
    } = event.detail;
    this.setData({
      manufactor:[]
    })
    this.setData({
      showPopup1: false,
      manufactor:this.data.manufactor.concat(value)
    });
    console.log(this.data.manufactor)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
    //获取厂家信息：
    this.fetchManufacturerList();
    //获取user信息：
    this.fetchuserList();
  },
  //获取厂家信息：
  fetchManufacturerList: function () {
    wx.cloud.callFunction({
      name: 'getManufactorList',
      success: res => {
        if (res.result.success) {
          console.log(res.result.data)
          let nameArray2 = res.result.data.map(item => item.name)
          this.setData({
            manufacturerList: nameArray2
          });
        } else {
          wx.showToast({
            title: 'Failed to fetch data',
            icon: 'none'
          });
        }
      },
      fail: err => {
        // console.error('Failed to call cloud function:', err);
        wx.showToast({
          title: 'Failed to fetch data',
          icon: 'none'
        });
      }
    });
  },
  // 开票类型
  billingTypeonChange(e) {
    this.setData({
      billingType: e.detail
    })
    console.log(this.data.billingType)
  },
  // 是否完成
  horizontalonChange(e) {
    this.setData({
      orderCompleted: e.detail
    })
  },
  // 是否售后
  afterSaleonChange(e) {
    this.setData({
      afterSale: e.detail
    })
  },

  //获取User list
  fetchuserList: function () {
    wx.cloud.callFunction({
      name: 'gitUserList',
      success: res => {
        // console.log(res)
        if (res.result.success) {
          let nameArray = res.result.data.map(item => item.username)
          this.setData({
            userList: nameArray
          });

        } else {
          wx.showToast({
            title: 'Failed to fetch data',
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('Failed to call cloud function:', err);
        wx.showToast({
          title: 'Failed to fetch data',
          icon: 'none'
        });
      }
    });
  },

  //收集填写的信息并调用云函数写入到数据库
  newAddOrder: function (e) {
    wx.cloud.callFunction({
      name: 'createOrder',
      data: {
        user: this.data.user, //用户
        manufactor: this.data.manufactor, //厂家
        orderNumber: this.data.orderNumber, //订单号
        taobaoNumber: this.data.taobaoNumber, //淘宝订单号
        // oddNumber: this.data.oddNumber, //单号
        advancePayment: this.data.advancePayment, //预付款
        orderTime: this.data.orderTime, //下单时间
        expectDeliTime: this.data.expectDeliTime, //预际交货时间
        realityTime: this.data.realityTime, //实际交货时间
        customerAddress: this.data.customerAddress, //地址
        orderCompleted: this.data.orderCompleted, //是否完成
        afterSale: this.data.afterSale, //售后
        remarks: this.data.remarks, //评论
        billingType: this.data.billingType, //开票类型
        createdAt: this.data.currentTime,
        updatedAt: this.data.currentTime
      },
      success: res => {
        if (res.result.success) {
          wx.showToast({
            title: '订单创建成功',
            icon: 'success',
            duration: 2000 // 持续时间，单位毫秒
          });
          wx.showToast({
            title: '操作成功',
            icon: 'success',
            
          });
          console.log(this.data.manufactor,"new")
          wx.navigateTo({
            url: `/pages/PartsCatalog/PartsCatalog?orderNumber=${this.data.orderNumber}&afterSale=${this.data.afterSale}&user=${this.data.user}&manufactor=${JSON.stringify(this.data.manufactor[0])}`,
          })
          // 清空表单或跳转至其他页面
        } else {
          wx.showToast({
            title: '订单创建失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        // console.error('Failed to call cloud function:', err);
        wx.showToast({
          title: '订单创建失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})